/* eslint-disable no-fallthrough */
//导出echarts图片
import * as echarts from 'echarts/core';
import { ElMessage } from 'element-plus';
import { store } from '@/store/index';
import router from '@/router';
import BenzAMRRecorder from 'benz-amr-recorder';
import { nextTick, onUnmounted } from 'vue';
import _ from 'lodash';

// import content from '@/store/modules/content';
export const deepClone = (obj: any) => {
    const result = typeof obj.splice === 'function' ? [] : {};
    if (obj && typeof obj === 'object') {
        for (const key in obj) {
            if (obj[key] && typeof obj[key] === 'object') {
                result[key] = deepClone(obj[key]);
                result[key] = obj[key];
            }
        }
        return result;
    }
    return obj;
};
export const getSetionId = (key: string, data: any[] = []) => {
    const arr: number[] = [];
    if (data.length > 0) {
        data.forEach((item: any) => {
            if (item?.hasOwnProperty(key)) {
                arr.push(item[key]);
            }
        });
    }
    return arr;
};
// yyyy-MM-dd hh:mm:ss
export const DFormat = (date: any, fmt: string) => {
    if (typeof date === 'number') {
        date = new Date(date);
    }
    const o = {
        'M+': date.getMonth() + 1, //月份
        'd+': date.getDate(), //日
        'h+': date.getHours(), //小时
        'm+': date.getMinutes(), //分
        's+': date.getSeconds(), //秒
        'q+': Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (const k in o)
        if (new RegExp('(' + k + ')').test(fmt))
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    return fmt;
};

// 单位秒
export const SFormat = (v: number): string => {
    let time = '';
    const h = Math.floor(v / 3600);
    const m = Math.floor((v % 3600) / 60);
    const s = (v % 216000) - (h * 3600 + m * 60);
    // 时
    if (h && m && s) time = `${h}时${m}分${s}秒`;
    if (h && !m && !s) time = `${h}时`;
    if (h && m && !s) time = `${h}时${m}分`;
    if (h && !m && s) time = `${h}时${m}分${s}秒`;
    // 分
    if (!h && m && s) time = `${m}分${s}秒`;
    if (!h && m && !s) time = `${m}分`;
    // 秒
    if (!h && !m && s) time = `${s}秒`;
    return time || '--';
};

// 判断是否为空

export const IsNotEmpty = (str: any) => {
    const type = Object.prototype.toString.call(str);
    switch (type) {
        case '[object String]':
        case '[object Number]':
        case '[object Boolean]':
        case '[object Undefined]':
        case '[object Null]':
            return !!str;
        case '[object Object]':
            return Object.keys(str).length > 0;
        case '[object Array]':
            return str.length > 0;
        default:
            return true;
    }
};

//获取时间1
export const getDay = (day: any, type?: boolean) => {
    const today = new Date();
    const targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds);
    const tYear = today.getFullYear();
    let tMonth = today.getMonth();
    let tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return type
        ? tYear + '-' + tMonth + '-' + tDate + ' ' + '23:59:59'
        : tYear + '-' + tMonth + '-' + tDate + ' ' + '00:00:00';
};

//获取时间2
export const getTimes = (day: any) => {
    const today = new Date();
    const targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds);
    const tYear = today.getFullYear();
    let tMonth = today.getMonth();
    let tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + '-' + tMonth + '-' + tDate;
};
// 活动时间筛选
export const getFilterDate = (date?: any) => {
    let day = 0;
    let endDate = '00-00-00 23:59:59';
    if (date) {
        const nowDate = new Date(DFormat(new Date(), 'yyyy-MM-dd')).getTime(); // 当前时间
        const activityDate = new Date(date.split(' ')[0]).getTime(); // 活动时间
        const time = nowDate - activityDate; // 时间差
        day = Math.ceil(time / (3600000 * 24)); // 时间差的天数
        endDate = date;
    }
    const endHms = endDate.split(' ')[1];
    const resData = [
        [getDay(-(1 + day)), `${getTimes(-(1 + day)) + ' ' + '23:59:59'}`],
        [getDay(-(6 + day)), `${getTimes(-(0 + day)) + ' ' + endHms}`],
        [getDay(-(29 + day)), `${getTimes(-(0 + day)) + ' ' + endHms}`]
    ];
    return resData;
};

const doHandleMonth = (month: any) => {
    let m = month;
    if (month.toString().length == 1) {
        m = '0' + month;
    }
    return m;
};

export const getVideoThumb = (url: string) => {
    return url + '?x-oss-process=video/snapshot,t_0,f_jpg,w_320,h_240,m_fast';
};
export const getVideoImage = (url: string, w?: number, h?: number) => {
    return `${url}?x-oss-process=video/snapshot,t_0,f_jpg,w_${w},h_${h},m_fast`;
};

export const formatTel = (str = '') => {
    const pat = /(\d{3})\d*(\d{4})/;
    return str?.replace(pat, '$1****$2');
};
//导出echarts图片
export const export2Img = (val: any, name: any) => {
    const Echarts = echarts.init(val);
    const picInfo = Echarts.getConnectedDataURL({
        type: 'png',
        pixelRatio: 1.5,
        backgroundColor: '#fff'
    });
    const a = document.createElement('a');
    a.download = name;
    a.style.display = 'none';
    a.href = picInfo;
    document.body.appendChild(a);
    if (a.href == 'data:,') {
        ElMessage.error('暂无数据可导出');
    } else {
        a.click();
        URL.revokeObjectURL(a.href); // 释放URL 对象
        document.body.removeChild(a);
    }
};
// 上传文件类型
const fileTYpe = {
    '.pdf': '/static/file/pdf.png',
    '.doc': '/static/file/doc.png',
    '.docx': '/static/file/doc.png',
    '.xls': '/static/file/xls.png',
    '.xlsx': '/static/file/xls.png',
    '.ppt': '/static/file/ppt.png',
    '.pptx': '/static/file/ppt.png',
    '.png': '/static/file/pic.png',
    '.jpg': '/static/file/pic.png',
    '.jpeg': '/static/file/pic.png',
    '.text': '/static/file/text.png',
    '.txt': '/static/file/text.png'
};
// 获取对应得图标
export const getSuffixIcon = (str: string) => {
    if (str) {
        const suffix = str.substring(str.lastIndexOf('.'));
        const types = Object.keys(fileTYpe);
        if (types.includes(suffix)) {
            return fileTYpe[suffix];
        } else {
            return '/static/file/file.png';
        }
    } else {
        return '/static/file/file.png';
    }
};
// 最大图片的尺寸
export const getImageMaxWH = (w: number, h: number, W = 1440, H = 1080) => {
    const scale = w / h;
    if (w >= W) {
        w = W;
        h = parseInt(W / scale);
    }
    if (h >= H) {
        h = H;
        w = parseInt(h * scale);
    }
    return { w, h };
};
//获取上传图片的宽高
export const getImage_wh = (file: any) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e: any) {
            const img = new Image();
            img.src = e.target.result;
            img.onload = async function () {
                const W = img.width;
                const H = img.height;
                const res = await getImageMaxWH(W, H);
                const w = res.w;
                const h = res.h;
                resolve({ w, h, W, H });
            };
        };
    });
};

// 获取视频、音频的时长
export const playTime = (file: any, tag = 'video') => {
    return new Promise((resolve, reject) => {
        const ext = file.name.substring(file.name.lastIndexOf('.'));
        // 音频格式。amr  特殊处理
        if (ext === '.amr') {
            const amr = new BenzAMRRecorder();
            amr.initWithBlob(file)
                .then((res: any) => {
                    const duration = amr.getDuration();
                    resolve(duration);
                })
                .catch((err: any) => {
                    reject(err);
                });
        } else {
            const reader = new FileReader();
            reader.onload = () => {
                const oVideo = document.createElement(tag);
                oVideo.setAttribute('src', reader.result);
                oVideo.oncanplay = () => {
                    resolve(oVideo.duration);
                };
                oVideo.onerror = e => {
                    reject(e);
                };
            };
            reader.readAsDataURL(file);
        }
    });
};
// 早中晚
export const getTimeState = () => {
    const hours = new Date().getHours();
    let state = ``;
    if (hours >= 0 && hours <= 10) {
        state = `早上好，`;
    } else if (hours > 10 && hours <= 14) {
        state = `中午好，`;
    } else if (hours > 14 && hours <= 18) {
        state = `下午好，`;
    } else if (hours > 18 && hours <= 24) {
        state = `晚上好，`;
    }
    return state;
};

//计算两个日期相差的天数
export const getDiffDay = (date_1: any, date_2: any, type: boolean) => {
    // 计算两个日期之间的差值
    const myDate_1 = Date.parse(date_1);
    const myDate_2 = Date.parse(date_2);
    // 将两个日期都转换为毫秒格式，然后做差
    const diffDate = Math.abs(myDate_1 - myDate_2); // 取相差毫秒数的绝对值
    const totalDays = Math.floor(diffDate / (1000 * 3600 * 24)); // 向下取整
    return type ? totalDays + 1 : totalDays; // 相差的天数
};

// 按钮权限
export const auth = (codeList: Array<string>, code: string) => {
    codeList = store.state.menu?.buttonCode || [];

    if (!codeList || !Array.isArray(codeList) || !code) return true;

    return codeList.includes(code);
};
/**
 * 直接下载指定链接
 * @param {*} url 传入文件的全链接
 * @param {*} fileName 文件名字
 */
export function downFile(url: any, fileName: any) {
    fetch(url).then(res =>
        res.blob().then(blob => {
            const a = document.createElement('a');
            a.href = window.URL.createObjectURL(blob);
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        })
    );
}
/**
 * 格式化数值999,999,999.99
 * @param {*} num 传入的数字
 */
export function numFormat(num: number | string) {
    return num ? num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 0;
}
// 处理单张图片
export const downloadByBlob = (url: any, name: any) => {
    const download = (href: any, name: any) => {
        const eleLink = document.createElement('a');
        eleLink.download = name;
        eleLink.href = href;
        eleLink.click();
        eleLink.remove();
    };

    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.src = url;
    image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, image.width, image.height);
        canvas.toBlob(blob => {
            const url = URL.createObjectURL(blob);
            download(url, name);
            // 用完释放URL对象
            URL.revokeObjectURL(url);
        });
    };
};

/**
 * 下载文件
 * @param {*} href 传入文件的全链接
 */
export function downloadFile(href: string, target?: string) {
    const downloadElement = document.createElement('a');
    downloadElement.href = href;
    downloadElement.target = target ?? '_self';
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
}

// 收起展开
export const AFold = (val: boolean, dom: string) => {
    const oDom = document.querySelector(dom);
    const oDOM_W = oDom.offsetWidth;
    const Item_W = oDom.children[0]?.offsetWidth;
    const s = Math.floor(oDOM_W / Item_W);
    // eslint-disable-next-line no-unsafe-optional-chaining
    const items = [...oDom?.children];
    const data = items.slice(s - 1, items.length - 1);
    data.forEach((item: any) => (item.style.display = val ? 'block' : 'none'));
};
// 表格高度
export const tableH = (dom: string, flag: boolean) => {
    const H = document.body.clientHeight || document.documentElement.clientHeight;
    const h = document.querySelector(dom)?.offsetTop || 0;
    const clientTop = document.querySelector(dom)?.clientTop || 0;
    if (flag) {
        return H - h - 145;
    } else {
        return H - h - 145 + 'px';
    }
};
/**
 * @description: 树的高度
 * @param {string} dom
 * @param {*} gap 差值
 * @return {*}
 */
export const treeH = (dom: string, gap = 274) => {
    const H = document.body.clientHeight || document.documentElement.clientHeight;
    const h = document.querySelector(dom)?.offsetTop || 0;
    return H - h - gap;
};
// 窗口尺寸大小
export const reSize = (cb: any) => {
    window.addEventListener('resize', () => cb(), true);
};

export const getRandomKey = (num?: number): string => {
    const t = 'ABCDEFGHJKMNPQRSTWXYZ0123456789abcdefhijkmnprstwxyz?_*%$#';
    let total = '';
    let n = 0;
    if (typeof num === 'number' && num > 0 && num < 21) {
        while (n < num) {
            const add = t[Math.round(Math.random() * Number(t.length - 1))];
            total = `${total}${add}`;
            n++;
        }
    } else {
        total = getRandomKey(16);
    }
    return total;
};
// 是否地产用户/
export const useCheckReal = () => {
    const isReal = store.getters['user/getAccountInfo']?.base_info?.tenant_type === 2;
    return isReal;
};
export const timeSlotChange = val => {
    let startTime, endTime;
    const now = new Date(); //当前日期
    const nowDayOfWeek = now.getDay(); //今天本周的第几天
    const nowDay = now.getDate(); //当前日
    const nowMonth = now.getMonth(); //当前月
    const nowYear = now.getFullYear(); //当前年
    const jd = Math.ceil((nowMonth + 1) / 3);
    function formatDate(date) {
        const myYear = date.getFullYear();
        let myMonth = date.getMonth() + 1;
        let mmyWeekDay = date.getDate();
        if (myMonth < 10) {
            myMonth = '0' + myMonth;
        }
        if (mmyWeekDay < 10) {
            mmyWeekDay = '0' + mmyWeekDay;
        }
        return myYear + '-' + myMonth + '-' + mmyWeekDay;
    }
    switch (val) {
        case '本周':
            startTime = new Date(nowYear, nowMonth, nowDay + 1 - (nowDayOfWeek == 0 ? 1 : nowDayOfWeek));
            endTime = new Date(nowYear, nowMonth, nowDay + 7 - (nowDayOfWeek == 0 ? 1 : nowDayOfWeek));
            break;
        case '本月':
            startTime = new Date(nowYear, nowMonth, 1);
            endTime = new Date(nowYear, nowMonth + 1, 0);
            break;
        case '本季度':
            startTime = new Date(nowYear, (jd - 1) * 3, 1);
            endTime = new Date(nowYear, jd * 3, 0);
            break;
        case '本年':
            startTime = new Date(nowYear, 0, 1);
            endTime = new Date(nowYear, 11, 31);
            break;
    }
    return [formatDate(startTime) + ' 00:00:00', formatDate(endTime) + ' 23:59:59'];
};

/** 欢迎语在当前光标除、插入内容.
 * @param {String} selectorId id选择器
 * @param {Object} form 插入数据的对象
 * @param {String} path 字段名，支持[0]， . 的方式
 */
export const useInsertWelcomeContent = (selectorId: string, form: object, path: string) => {
    let onInsertText: any = (v: any) => {
        const el: any = document.getElementById(selectorId);
        const inpIndex = el.selectionStart;
        const content = _.get(form, path, '');
        const start = `${content.substring(0, inpIndex)}${v}`;
        const end = content.substring(inpIndex, content.length);
        _.set(form, path, `${start}${end}`);
        el.focus();
        nextTick(() => {
            el.selectionStart = start.length;
            el.selectionEnd = start.length;
        });
    };
    onUnmounted(() => {
        onInsertText = null;
    });
    return onInsertText;
};

// sleep
export const sleep = (num = 1): Promise<boolean> => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(true);
        }, num);
    });
};
// 获取图片地址的宽高
export const getImageUrlWH = (img: any) => {
    const image = new Image();
    image.crossOrigin = '';
    image.src = img;
    return new Promise((resolve, reject) => {
        image.onload = function () {
            const { width, height } = image;
            image.onload = null;
            resolve({ width, height });
        };
    });
};

/**
 * @description: 格式化选择素材数据
 * @param {any} state
 * @return {*}
 */
export const formatMaterialParams = (state: any) => {
    const { content, material } = state;
    const media_content: any[] = [];
    let welcome_friend_attachment_ids: any[] = [];
    const local_content: any[] = [];
    const local_link: any[] = [];
    if (material.length) {
        material.forEach((item: any) => {
            const { type, id: media_content_id, local: local = false, code: code = '' } = item;
            const { link_title, link_url, link_decs, content, link_share_image } = item;
            if (local) {
                switch (Number(type)) {
                    case 6:
                        local_link.push({ link_title, link_url, link_decs, content, link_share_image });
                        break;
                    default:
                        local_content.push({ type, code });
                        break;
                }
            } else {
                media_content.push({ type, media_content_id });
            }
        });
        welcome_friend_attachment_ids = media_content.map(item => item.media_content_id);
    }
    return { content, media_content, local_content, local_link, welcome_friend_attachment_ids };
};

/**
 * @description: 格式化选择素材数据（增加个删除分开计算的方式）
 * @param {any} state
 * @return {*}
 */
export const formatMaterialParams2 = (state: any) => {
    const { content, material, restIds, newMaterials } = state;
    const media_content: any[] = [];
    const welcome_friend_attachment_ids: any[] = [];
    const local_content: any[] = [];
    const local_link: any[] = [];
    if (newMaterials.length) {
        newMaterials.forEach((item: any) => {
            const { type, id: media_content_id, local: local = false, code: code = '' } = item;
            const { link_title, link_url, link_decs, content, link_share_image } = item;
            if (local) {
                switch (Number(type)) {
                    case 6:
                        local_link.push({ link_title, link_url, link_decs, content, link_share_image });
                        break;
                    default:
                        local_content.push({ type, code });
                        break;
                }
            } else {
                media_content.push({ type, media_content_id });
            }
        });
    }
    return { content, media_content, local_content, local_link, welcome_friend_attachment_ids: restIds };
};

/**
 * @description: 欢迎语 选择素材组件类型 配置
 * @return {*}
 */
export const materialTabs = [
    {
        type: '0',
        icon: '/static/file/pic.png',
        name: '文本',
        field: '',
        id: '1'
    },
    {
        type: '1',
        icon: '/static/file/pic.png',
        name: '图片',
        field: 'file_name',
        id: '2'
    },
    {
        type: '2',
        icon: '/static/file/mov.png',
        name: '视频',
        field: 'file_name',
        id: '4'
    },
    {
        type: '3',
        icon: '/static/file/link.png',
        name: '链接',
        field: 'title',
        id: '6'
    },
    {
        type: '4',
        icon: '/static/file/mp3.png',
        name: '音频',
        field: 'file_name',
        id: '3'
    },
    {
        type: '5',
        icon: '/static/file/ysb.png',
        name: '文件',
        field: '',
        id: '5'
    },
    {
        type: '6',
        icon: '/static/file/wbgg.png',
        name: '抽奖',
        field: 'activity_name',
        id: '8'
    },
    {
        type: '7',
        icon: '/static/file/shop.png',
        name: '电商',
        field: 'product_name',
        id: '99'
    },
    {
        type: '8',
        icon: '/static/file/shop.png',
        name: '电商',
        field: 'page_name',
        id: '99'
    },
    {
        type: '9',
        icon: '/static/file/form.png',
        name: '收集表',
        field: 'title',
        id: '27'
    },
    {
        type: '10',
        icon: '/static/file/official.png',
        name: '公众号',
        field: '',
        id: '15'
    },
    {
        type: '11',
        icon: '/static/file/miniApp.png',
        name: '小程序',
        field: 'title',
        id: '11'
    }
];

/**
 * @description: 欢迎语 选择素材组件 映射 map对象
 * @param {*} any
 * @return {*}
 */
export const getHashTabs = (): any[] => {
    return materialTabs.reduce((pre: any, cur: any) => {
        return { ...pre, [cur.type]: cur };
    }, {});
};

/**
 * @description:
 * @param {any} data
 * @return {*}
 */
export const mapOfficialAccountsData = (data: any) => {
    const list = [
        { name: '', type: 1, iconUrl: '/static/file/official.png' },
        { name: '', type: 2, iconUrl: '/static/file/text.png' },
        { name: '视频', type: 3, iconUrl: '/static/file/mov.png' },
        { name: '音频', type: 4, iconUrl: '/static/file/mp3.png' },
        { name: '图片', type: 5, iconUrl: '/static/file/pic.png' }
    ];
    let { cover: icon } = data;
    const { type: articleType, id, title } = data;
    const targetItem = list.find(el => el.type === articleType);
    const name = targetItem?.name || title;
    const iconUrl = targetItem?.iconUrl;
    const type = '10';
    if (articleType !== 1) {
        icon = iconUrl;
    }
    return { type, name, icon, id, articleType };
};

/**
 * @description:
 * @param {any} item
 * @return {*}
 */
export const mapOfficialAccountsAlreadyData = (item: any): any[] => {
    const list = [
        { name: '', type: 1, iconUrl: '/static/file/official.png' },
        { name: '', type: 2, iconUrl: '/static/file/text.png' },
        { name: '视频', type: 3, iconUrl: '/static/file/mov.png' },
        { name: '音频', type: 4, iconUrl: '/static/file/mp3.png' },
        { name: '图片', type: 5, iconUrl: '/static/file/pic.png' }
    ];
    const { article_detail, official_article } = item;
    if (article_detail?.length) {
        return article_detail.map((ite: any) => {
            let { cover: icon } = ite;
            const { type: articleType, id, title } = ite;
            const targetItem = list.find(el => el.type === articleType);
            let name = targetItem?.name;
            const iconUrl = targetItem?.iconUrl;
            const type = '10';
            if (articleType !== 1) {
                icon = iconUrl;
            }
            if (articleType === 1 || articleType === 2) {
                name = title;
            }
            return { type, name, icon, id, articleType };
        });
    } else if (official_article) {
        let { cover: icon } = official_article;
        const { type: articleType, id, title, content } = official_article;
        const targetItem = list.find(el => el.type === articleType);
        const name = targetItem?.name || title || content;
        const iconUrl = targetItem?.iconUrl;
        const type = '10';
        if (articleType !== 1) {
            icon = iconUrl;
        }
        return [{ type, name, icon, id, articleType }];
    } else {
        return [];
    }
};

/**
 * @description: 欢迎语数据回显 初始化  按照统一数据结构模式标准化参数
 * @param {any} data
 * @return {*}
 */
export const initMaterialData = (data: any[]): any[] => {
    const hashTabs = getHashTabs();
    return data.map((item: any) => {
        const {
            type,
            content_id,
            absolute_url,
            title,
            link_title,
            link_url,
            link_decs,
            link_share_image,
            code,
            appid,
            official_article,
            is_default_del: is_default_del = 2
        } = item;
        let { name } = item;
        let officialAccountsData = {};
        const id = content_id;
        const imgUrl = absolute_url;
        let url = '';
        let mpUrl = '';
        const videoUrl = `${absolute_url}?x-oss-process=video/snapshot,t_0,f_jpg,w_320,h_240,m_fast`;
        let linkUrl = '';
        let icon = hashTabs[type.toString()].icon;
        const local = !content_id && !(is_default_del === 1);
        let content = '';
        switch (type) {
            case 1:
                // imgUrl = item.media_file.absolute_url
                name = item.name;
                break;
            case 2:
                url = item.absolute_url;
                // videoUrl = `${absolute_url}?x-oss-process=video/snapshot,t_0,f_jpg,w_320,h_240,m_fast`
                break;
            case 3:
                name = link_title;
                linkUrl = link_share_image;
                content = link_decs;
                break;
            case 4:
                break;
            case 5:
                icon = getSuffixIcon(name);
                url = link_url;
                break;
            case 6:
                name = link_title;
                content = link_decs;
                break;
            case 7:
                content = link_decs;
            case 8:
                content = link_decs;
            case 9:
                name = link_title;
                content = link_decs;
                break;
            case 10:
                officialAccountsData = mapOfficialAccountsData(official_article);
                break;
            case 11:
                name = title;
                mpUrl = absolute_url;
                content = link_decs;
                break;
        }
        return {
            type: type.toString(),
            code,
            link_title,
            link_url,
            link_decs,
            link_share_image,
            local,
            icon,
            name,
            id,
            url,
            imgUrl,
            mpUrl,
            videoUrl,
            linkUrl,
            appid,
            content,
            is_default_del,
            ...officialAccountsData
        };
    });
};

/**
 * @description: 选择已有欢迎语后 格式化数据用于欢迎语组件显示
 * @param {any} data
 * @return {*}
 */
export const initAlreadyMaterialData = (data: any[]): any[] => {
    const hashTabs = getHashTabs();
    const arr: any[] = [];
    let officialAccountsArr: any[] = [];
    data.forEach((item: any) => {
        const { type, content_id: id, is_default_del: is_default_del = 2 } = item;
        let name = item.file_name ?? item.media_file?.name;
        const code = item.media_file?.code ?? '';
        const link_title = item.media_file?.link_title ?? item?.link_title ?? '';
        const link_url = item.media_file?.link_url ?? item?.link_url ?? '';
        const link_decs = item.media_file?.link_decs ?? item?.link_decs ?? '';
        const link_share_image = item.media_file?.link_share_image ?? item?.link_share_image ?? '';
        let title = '';
        let icon = hashTabs[type.toString()].icon;
        let imgUrl = '';
        let mpUrl = '';
        let videoUrl = '';
        let linkUrl = '';
        const local = !id && !(is_default_del === 1);
        switch (Number(type)) {
            case 1:
                imgUrl = item.absolute_url ?? item.media_file?.absolute_url;
                break;
            case 2:
                videoUrl =
                    item.thumbnail_url ??
                    `${item.media_file?.absolute_url}?x-oss-process=video/snapshot,t_0,f_jpg,w_320,h_240,m_fast`;
                break;
            case 3:
                name = item.title ?? item.link_title;
                linkUrl = item.cover_image_url ?? item.link_share_image;
                title = item.title || item.link_title;
                break;
            case 4:
                break;
            case 5:
                name = item.mediaFileInfo?.name ?? item.media_file?.name;
                icon = getSuffixIcon(item.mediaFileInfo?.absolute_url || item.media_file?.absolute_url);
                title = item.mediaFileInfo?.name ?? item.media_file?.name;
                break;
            case 6:
                name = item.activity_name;
                break;
            case 7:
                name = item.retail_product
                    ? item.retail_product?.product_name
                    : item.product_name
                    ? item.product_name
                    : item.page_name;
                break;
            case 8:
                name = item.page_name ? item.page_name : item.product_name;
                break;
            case 9:
                name = item.title || item.collect_form?.title;
                break;
            case 10:
                officialAccountsArr = mapOfficialAccountsAlreadyData(item);
                break;
            case 11:
                name = item.title ?? item.miniprogram?.title;
                mpUrl = item.image_url ?? item.miniprogram?.image_url;
                break;
        }
        if (type === 10) {
            arr.push(...officialAccountsArr);
        } else {
            const mItem = {
                type: type.toString(),
                code,
                link_title,
                link_url,
                link_decs,
                link_share_image,
                local,
                icon,
                name,
                id,
                imgUrl,
                mpUrl,
                videoUrl,
                linkUrl,
                is_default_del
            };
            arr.push(mItem);
        }
    });
    return arr;
};

/**
 * @description: 新建编辑页面 获取中间内容区域的高度
 * @param {number} type
 * @return {*}
 */
export const getContentHeight = (type?: number | undefined): string => {
    const clientHeight = document.documentElement.clientHeight;
    let distance = 0;
    if (type) {
        if (type <= 10) {
            switch (type) {
                case 1:
                    // 254   只有底栏或者头栏的中间内容区域高度
                    distance = 238;
                    break;
                case 2:
                    // 380   有头栏和底栏的中间内容区域高度
                    distance = 364;
                    break;
                default:
                    distance = 238;
                    break;
            }
            return `${clientHeight - distance}px`;
        } else if (type > 10) {
            distance = type;
        }
    } else {
        distance = 238;
    }
    return `${clientHeight - distance}px`;
};

/**
 * @description:
 * @param {any} url
 * @return {*}
 */
export const loadJS = function (url: any) {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';

        // IE
        if (script.readyState) {
            script.onreadystatechange = function () {
                if (script.readyState == 'loaded' || script.readyState == 'complete') {
                    script.onreadystatechange = null;
                    resolve();
                }
            };
        } else {
            // 其他浏览器
            script.onload = function () {
                resolve();
            };
        }

        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    });
};

export const defaultTime = () => {
    const result: [Date, Date] = [new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)];
    return result;
};

/**
 * @description: 统计数据格式优化
 * @param {number} data
 * @return {*}
 */
export const formatStatisticsData = (data?: number | string | undefined | null): string => {
    if (Number(data)) {
        const arr = Number(data).toString().split('').reverse();
        let numList = arr.reduce((pre: any[], cur: string) => {
            if (pre.length) {
                if (pre[pre.length - 1].length % 3 === 0) {
                    pre.push([cur]);
                } else {
                    pre[pre.length - 1].push(cur);
                }
            } else {
                pre = [[cur]];
            }
            return pre;
        }, []);
        numList = numList.map(item => (item = item.reverse().join(''))).reverse();
        return numList.join(',');
    } else {
        return '0';
    }
};

/**
 * @description: 判断文字内容是否超出容器
 * @param e
 * @param type type:2-宽度或者高度超过都算溢出,适用于多行溢出
 * @returns
 */
export const isTextBeyond = (e: any, type?: any) => {
    const ev = window.event || e;
    const textRange = (el: any) => {
        const textContent = el;
        const targetW = textContent.getBoundingClientRect().width;
        const targetH = textContent.getBoundingClientRect().height;
        const range = document.createRange();
        range.setStart(textContent, 0);
        range.setEnd(textContent, textContent.childNodes.length);
        const rangeWidth = range.getBoundingClientRect().width;
        const rangeHeight = range.getBoundingClientRect().height;
        if (type == 2) {
            return rangeWidth > targetW || rangeHeight > targetH;
        } else {
            return rangeWidth > targetW;
        }
    };
    return !textRange(ev.target);
};

/**
 * @description: 判断当前页面是否已缓存
 * @param {*} boolean
 * @return {*}
 */
export const isCachePage = (): boolean => {
    const keepAliveIncludes = store.getters['pageCache/keepAliveIncludes'];
    return keepAliveIncludes.includes(router.currentRoute.value.meta.code);
};

/**
 * 获取文案长度
 * @param text 文案
 * @param font 文字类型
 */
export const getTextWidth = (text: any, font: any) => {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    context.font = font;
    const metrics = context.measureText(text);
    return metrics.width;
};
